package ui.fragment;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.SystemClock;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.netease.neliveplayer.sdk.NEDynamicLoadingConfig;
import com.netease.neliveplayer.sdk.NELivePlayer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import base.BaseBean;
import base.fragment.BaseNetFragment;
import bean.UnreadMsgBean;
import event.MainPageEvent;
import student.andlei.com.student.R;
import ui.activity.AddNewNoteActivity;
import ui.activity.MainActivity;
import ui.activity.MessageActivity;
import ui.fragment.homepagefragment.AllFragment;
import ui.fragment.homepagefragment.CourseraFragment;
import ui.fragment.homepagefragment.ExerciseBookFragment;
import ui.fragment.homepagefragment.NoteFragment;
import ui.fragment.homepagefragment.PracticeFragment;
import ui.fragment.homepagefragment.PrePareFragment;
import ui.fragment.homepagefragment.ReviewFragment;
import ui.fragment.homepagefragment.TimeTableFragment;
import ui.fragment.homepagefragment.WorkFragment;
import utils.DensityUtil;
import utils.GsonUtils;
import view.sdk.model.SDKOptions;


/**
 * 首页
 */
public class HomePageFragment extends BaseNetFragment{
    public final static String TAG ="HomePageFragment";
    private RadioGroup rpTab;
    private RadioButton rb_all,
            rb_timetable,
            rb_prepare,
            rb_review,
            rb_course,
            rb_work,
            rb_practice,
            rb_exercisebook,
            rb_note;
    private Fragment allFragment,
            courseraFragment,
            exercisebookFragment,
            noteFragment,
            practiceFragment,
            prepareFragment,
            reviewFragment,
            timetableFragment,
            workFragment;
    private ImageView img_msg;
    public TextView tv_msg_num;
    private Button bt_addnotebook;
    private int screenWidth,screenHeight;
    /**   6.0权限处理     **/
    private boolean bPermission = false;
    private final int WRITE_PERMISSION_REQ_CODE = 100;
    private SDKOptions config;
    public static Fragment getInstance() {
        return new HomePageFragment();
    }
    @Override
    public void success(String action, BaseBean baseBean) {
        if(baseBean.code == 200){
            if(action.equals("personal/getUnreadMsg")){
                UnreadMsgBean bean = (UnreadMsgBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean, UnreadMsgBean.class);
                if (bean.count <= 0) {
                    tv_msg_num.setVisibility(View.GONE);
                } else {
                    tv_msg_num.setText(bean.count + "");
                }
            }else if(action.equals("Qa/getNewsNumber")){
                UnreadMsgBean bean = (UnreadMsgBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean,UnreadMsgBean.class);
                if(bean.count>0){
                    MainActivity.img_red_point.setText(bean.count+"");
                    MainActivity.img_red_point.setVisibility(View.VISIBLE);
                }else {
                    MainActivity.img_red_point.setVisibility(View.GONE);
                }
            }
        }else {
            toast(baseBean.getMsg());
        }


    }

    @Override
    public void error(String action, Throwable e) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_homepage;
    }
    private boolean checkPublishPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> permissions = new ArrayList<>();
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_PHONE_STATE)) {
                permissions.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (permissions.size() != 0) {
                ActivityCompat.requestPermissions(getActivity(),
                        (String[]) permissions.toArray(new String[0]),
                        WRITE_PERMISSION_REQ_CODE);
                return false;
            }
        }
        return true;
    }
    @Override
    protected void findViews() {
        EventBus.getDefault().register(this);
        /**   6.0权限申请     **/
        bPermission = checkPublishPermission();
        config = new SDKOptions();
        //动态加载
        config.dynamicLoadingConfig = new NEDynamicLoadingConfig();
        //是否开启动态加载功能，默认关闭
//		config.dynamicLoadingConfig.isDynamicLoading = true;
        config.dynamicLoadingConfig.isArmeabi = true;
        config.dynamicLoadingConfig.onDynamicLoadingListener = mOnDynamicLoadingListener;
        config.supportDecodeListener = mOnSupportDecodeListener;
        img_msg = getView(R.id.img_msg);
        tv_msg_num = getView(R.id.tv_msg_number);
        rpTab = getView(R.id.rd_group);
        rb_all = getView(R.id.rb_all);
        rb_timetable = getView(R.id.rb_timetable);
        rb_prepare = getView(R.id.rb_prepare);
        rb_review = getView(R.id.rb_review);
        rb_course = getView(R.id.rb_course);
        rb_work = getView(R.id.rb_work);
        rb_practice = getView(R.id.rb_practice);
        rb_exercisebook = getView(R.id.rb_exercisebook);
        rb_note = getView(R.id.rb_note);
        bt_addnotebook = getView(R.id.bt_notebook);
    }
    private long clickTime=0;
    @Override
    protected void formatViews() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;

        img_msg.setOnClickListener(this);
        bt_addnotebook.setVisibility(View.VISIBLE);
        bt_addnotebook.setOnTouchListener(new View.OnTouchListener() {
            int lastX, lastY; // 记录移动的最后的位置
            private int btnHeight;

            public boolean onTouch(View v, MotionEvent event) {
                // 获取Action
                int ea = event.getAction();
                switch (ea) {
                    case MotionEvent.ACTION_DOWN: // 按下
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        clickTime = SystemClock.uptimeMillis();
                        break;
                    case MotionEvent.ACTION_MOVE: // 移动
                        // 移动中动态设置位置
                        int dx = (int) event.getRawX() - lastX;
                        int dy = (int) event.getRawY() - lastY;
                        int left = v.getLeft() + dx;
                        int top = v.getTop() + dy;
                        int right = v.getRight() + dx;
                        int bottom = v.getBottom() + dy;
                        if (left < 0) {
                            left = 0;
                            right = left + v.getWidth();
                        }
                        if (right > screenWidth) {
                            right = screenWidth;
                            left = right - v.getWidth();
                        }
                        if (top < 0) {
                            top = 0;
                            bottom = top + v.getHeight();
                        }
                        if (bottom > (screenHeight- DensityUtil.dp2pxInt(85))) {
                            bottom = (screenHeight- DensityUtil.dp2pxInt(85));
                            top = bottom - v.getHeight();
                        }
                        v.layout(left, top, right, bottom);
                        // Toast.makeText(getActivity(), "position：" + left + ", " +
                        // top + ", " + right + ", " + bottom, 0)
                        // .show();
                        // 将当前的位置再次设置
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();
                        break;
                    case MotionEvent.ACTION_UP: // 抬起
                        if (SystemClock.uptimeMillis() - clickTime <= 100) {
                            //如果两次的时间差＜1s，就不执行操作
                            jumpTo(AddNewNoteActivity.class);
                        }
                }
                return false;
            }
        });

        rpTab.setOnCheckedChangeListener(mOnCheckedChangeListener);

    }

    RadioGroup.OnCheckedChangeListener mOnCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            hideAllFragment();
            switch (i) {
                //全部
                case R.id.rb_all:
                    bt_addnotebook.setVisibility(View.VISIBLE);
                    if (allFragment == null) {
                        allFragment = AllFragment.getInstance();
                    }
                    showFragment(allFragment);
                    break;
                //课表
                case R.id.rb_timetable:
                    bt_addnotebook.setVisibility(View.GONE);
                    if (timetableFragment == null) {
                        timetableFragment = TimeTableFragment.getInstance();
                    }
                    showFragment(timetableFragment);
                    break;
                //预习
                case R.id.rb_prepare:
                    bt_addnotebook.setVisibility(View.VISIBLE);
                    if (prepareFragment == null) {
                        prepareFragment = PrePareFragment.getInstance();
                    }
                    showFragment(prepareFragment);
                    break;
                //复习
                case R.id.rb_review:
                    bt_addnotebook.setVisibility(View.VISIBLE);
                    if (reviewFragment == null) {
                        reviewFragment = ReviewFragment.getInstance();
                    }
                    showFragment(reviewFragment);
                    break;
                //课程
                case R.id.rb_course:
                    bt_addnotebook.setVisibility(View.GONE);
                    if (courseraFragment == null) {
                        courseraFragment = AllFragment.getInstance();

                    }
                    showFragment(courseraFragment);
                    break;
                //作业
                case R.id.rb_work:
                    bt_addnotebook.setVisibility(View.VISIBLE);
                    if (workFragment == null) {
                        workFragment = WorkFragment.getInstance();
                    } else {
                        showFragment(workFragment);
                    }
                    break;
                //自主练习
                case R.id.rb_practice:
                    bt_addnotebook.setVisibility(View.GONE);
                    if (practiceFragment == null) {
                        practiceFragment = PracticeFragment.getInstance();
                    }
                    showFragment(practiceFragment);
                    break;
                //习题本
                case R.id.rb_exercisebook:
                    bt_addnotebook.setVisibility(View.GONE);
                    if (exercisebookFragment == null) {
                        exercisebookFragment = ExerciseBookFragment.getInstance();
                    }
                    showFragment(exercisebookFragment);
                    break;
                //笔记
                case R.id.rb_note:
                    bt_addnotebook.setVisibility(View.GONE);
                    if (noteFragment == null) {
                        noteFragment = NoteFragment.getInstance();
                    }
                    showFragment(noteFragment);

                    break;
            }
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MainPageEvent event) {
        if (event.firstPage == MainPageEvent.HOME_PAGE && event.secondPage == 5) {
            rb_all.setChecked(false);
            rb_timetable.setChecked(false);
            rb_prepare.setChecked(false);
            rb_review.setChecked(false);
            rb_course.setChecked(true);
            rb_work.setChecked(false);
            rb_practice.setChecked(false);
            rb_exercisebook.setChecked(false);
            rb_note.setChecked(false);
            mOnCheckedChangeListener.onCheckedChanged(rpTab, R.id.rb_course);
        }
    }

    @Override
    protected void formatData() {
        allFragment = AllFragment.getInstance();
        courseraFragment = CourseraFragment.getInstance();
        exercisebookFragment = ExerciseBookFragment.getInstance();
        noteFragment = NoteFragment.getInstance();
        practiceFragment = PracticeFragment.getInstance();
        prepareFragment = PrePareFragment.getInstance();
        reviewFragment = ReviewFragment.getInstance();
        workFragment = WorkFragment.getInstance();
        timetableFragment = TimeTableFragment.getInstance();
        addFragment(R.id.details_layout,allFragment);
        addFragment(R.id.details_layout,courseraFragment);
        addFragment(R.id.details_layout,exercisebookFragment);
        addFragment(R.id.details_layout,noteFragment);
        addFragment(R.id.details_layout,practiceFragment);
        addFragment(R.id.details_layout,prepareFragment);
        addFragment(R.id.details_layout,reviewFragment);
        addFragment(R.id.details_layout,workFragment);
        addFragment(R.id.details_layout,timetableFragment);
        hideAllFragment();
        showFragment(allFragment);

    }
    //隐藏所有Fragment
    public void hideAllFragment(){
        hideFragment(allFragment);
        hideFragment(courseraFragment);
        hideFragment(exercisebookFragment);
        hideFragment(noteFragment);
        hideFragment(practiceFragment);
        hideFragment(prepareFragment);
        hideFragment(reviewFragment);
        hideFragment(workFragment);
        hideFragment(timetableFragment);
    }
    @Override
    protected void getBundle() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.img_msg:
                jumpTo(MessageActivity.class);
//                if(!bPermission){
//                    toast("请先允许app所需要的权限");
//                    bPermission = checkPublishPermission();
//                    return;
//                }
//                if(config!=null && config.dynamicLoadingConfig!=null &&config.dynamicLoadingConfig.isDynamicLoading&&!NELivePlayer.isDynamicLoadReady()) {
//                    toast("请等待加载so文件");
//                    return;
//                }

//                Bundle bundle = new Bundle();
//                bundle.putString("media_type","videoondemand");
//                bundle.putString("decode_type","software");
//                // http://ohjdda8lm.bkt.clouddn.com/course/sample1.mp4
//                // http://jdvodqbt9dzw0.vod.126.net/jdvodqbt9dzw0/18c14535-b1e4-4a21-84d2-e560774df0ec.flv
//                bundle.putString("videoPath","http://jdvodqbt9dzw0.vod.126.net/jdvodqbt9dzw0/f50c3a97-98a7-4467-aefc-82089485e88c.flv");
//                jumpTo(VodActivity.class,bundle);
//                jumpTo(MessageActivity.class);
                break;
        }
    }
    private NELivePlayer.OnDynamicLoadingListener mOnDynamicLoadingListener = new NELivePlayer.OnDynamicLoadingListener() {
        @Override
        public void onDynamicLoading( NEDynamicLoadingConfig.ArchitectureType type,  boolean isCompleted) {
            Log.d(TAG, "type:"+type+"，isCompleted:"+isCompleted);
        }
    };

    private NELivePlayer.OnSupportDecodeListener mOnSupportDecodeListener = new NELivePlayer.OnSupportDecodeListener() {
        @Override
        public void onSupportDecode(boolean isSupport) {
            Log.d(TAG, "是否支持H265硬件解码 onSupportDecode isSupport:" + isSupport);
            //如果支持H265硬件解码，那么可以使用H265的视频源进行播放
        }
    };

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            post("Qa/getNewsNumber",BaseBean.class,false);
            post("personal/getUnreadMsg",BaseBean.class,false);
        }
    }
}
